﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web.Mvc;

namespace System.Web.Mvc.Html
{
    public static class HtmlExtensions
    {
        /// <summary>
        /// 可用客户端验证,输出javascript
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <returns></returns>
        public static MvcHtmlString EnableClientValidationJavascript(this HtmlHelper htmlHelper)
        {
            return htmlHelper.Partial("EnableClientValidation");
        }

        public static MvcHtmlString ShowRemindMsg(this HtmlHelper htmlHelper)
        {
            return htmlHelper.Partial("ViewMessage");
            //return new MvcHtmlString("");
        }

        public static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
        {
            return (((metadata.ShowForEdit && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
        }

        private static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText, IDictionary<string, object> htmlAttributes)
        {
            string str = labelText ?? (metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>()));
            if (string.IsNullOrEmpty(str))
            {
                return MvcHtmlString.Empty;
            }
            TagBuilder tagBuilder = new TagBuilder("label");
            tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
            tagBuilder.SetInnerText(str);
            foreach (var item in htmlAttributes)
            {
                if (item.Value != null)
                {
                    tagBuilder.Attributes.Add(item.Key, item.Value.ToString());
                }

            }

            return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal));
        }

        public static MvcHtmlString Label(this HtmlHelper html, string expression, object htmlAttributes)
        {
            IDictionary<string, object> attributes = ((IDictionary<string, object>)HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
            return LabelHelper(html, ModelMetadata.FromStringExpression(expression, html.ViewData), expression, null, attributes);

        }


    }
}
